package com.example.g5project.customer.model.param;

import com.example.g5project.customer.contants.Constant;
import com.example.g5project.customer.model.result.Result;
import com.google.common.primitives.Chars;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.apache.commons.lang3.StringUtils;

@Data
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class CustomerRegisterParam {

    private String name;

    private String phone;

    private String password;

    private String contactName;

    private String contactPhone;

    public Result check() {
        Result nameResult = this.checkName(this.name, "本人");
        if (!nameResult.isRight()) {
            return nameResult;
        }
        Result phoneCheckResult = this.checkPhone(this.phone, "本人");
        if (!phoneCheckResult.isRight()) {
            return phoneCheckResult;
        }
        if (StringUtils.isEmpty(this.password)) {
            return Result.error("密码不可为空");
        }
        Result contactNameResult = this.checkName(this.contactName, "紧急联系人");
        if (!contactNameResult.isRight()) {
            return contactNameResult;
        }
        Result emergencyNumberResult = this.checkPhone(this.contactPhone, "紧急联系人");
        if (!emergencyNumberResult.isRight()) {
            return emergencyNumberResult;
        }
        return Result.SUCCESS;
    }

    private Result checkPhone(String phone, String who) {
        if (StringUtils.isEmpty(phone)) {
            return Result.error(who + "手机号不可为空");
        }
        if (!Pattern.compile(Constant.PHONE_MATCHER).matcher(phone).matches()) {
            return Result.error("请输入正确的" + who + "手机号");
        }
        return Result.SUCCESS;
    }

    private Result checkName(String name, String who) {
        if (StringUtils.isEmpty(name)) {
            return Result.error(who + "姓名不可为空");
        }
        if (name.length() < 2 || name.length() > 32) {
            return Result.error(who + "姓名长度应在2-32个字符");
        }
        for (Character c : Chars.asList(Constant.NAME_LIMIT.toCharArray())) {
            if (name.contains(c.toString())) {
                return Result.error(who + "姓名中不能包含特殊字符: " + c);
            }
        }
        return Result.SUCCESS;
    }
}
